import socket
# from app import models

# server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# # socket主机
# socket_host = models.DefaultParams.objects.filter(name='socket_host')
# if param.exists():
#     socket_host = param.first().param_value
# else:
#     socket_host = '172.20.216.103'
#     models.DefaultParams.objects.create(name='socket_host', param_value=socket_host, is_static=True)
    
# # socket端口
# socket_port = models.DefaultParams.objects.filter(name='socket_port')
# if socket_port.exists():
#     socket_port = socket_port.first().param_value
# else:
#     socket_port = 9999
#     models.DefaultParams.objects.create(name='socket_port', param_value=socket_port, is_static=True)
    
# # socket线程数
# socket_threads_count = models.DefaultParams.objects.filter(name='socket_threads_count')
# if socket_threads_count.exists():
#     socket_threads_count = socket_threads_count.first().param_value
# else:
#     socket_threads_count = 1000
#     models.DefaultParams.objects.create(name='socket_threads_count', param_value=socket_threads_count, is_static=True)

socket_host = '172.20.216.103'
socket_port = 9999
socket_threads_count = 1000

# 第一个参数有: socket.AF_INET,  socket.AF_UNIX, 
# 第二个参数有: socket.SOCK_DGRAM, socket.SOCK_RAW, socket.SOCK_RDM， socket.SOCK_STREAM,
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.bind((socket_host, socket_port))
server_socket.listen(socket_threads_count)


# 下面这个while循环是监听客户端的连接请求
# 并接收客户端发送过来的消息
# 然后向客户端发送消息
# 最后关闭客户端连接
while True:
    client_socket, address = server_socket.accept()
    # 获取客户端发送过来的消息
    # 1024表示一次最多接收1024字节
    message = client_socket.recv(1024)
    print("Received from ",address,', message: ', message.decode())
    client_socket.send(b"Welcome to the server!")
    # 如果服务器收到了客户端发送过来的退出登录消息，那么就关闭客户端连接
    if message.decode() == 'exit':
        break
    
    # 关闭客户端连接
    # client_socket.close()
    
    
    client_socket.close()

